//
//  CreditCore.m
// 

#import "CreditCore.h"
#import "LoginViewController.h"
#import "GuideViewController.h"

#define kESUserDefaultsKey_CheckFreshLaunchAppVersion @"es_check_fresh_launch_app_version"


@implementation CreditCore

+ (CreditCore *)globleCore{
    
    static CreditCore *sharedCore;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedCore = [[CreditCore alloc]init];
    });
    return sharedCore;
}

- (id)init{
    self = [super init];
    if (self) {
       
    }
    return self;
}


+ (AppDelegate *)appDelegate{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

+ (UIWindow *)mainWindow{
    return [self appDelegate].window;
}

+ (UIViewController *)appRootViewController{
    return [[self mainWindow] rootViewController];
}

+ (void)deleteAllHTTPCookies{
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *c in cookieStorage.cookies) {
        [cookieStorage deleteCookie:c];
    }
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

+ (BOOL)isFreshLaunch:(NSString *)previousAppVersion{
    
    static NSString *previousVersion = nil;
    
    static BOOL _isFreshLaunch = NO;
    
    static dispatch_once_t onceToken;
   
    dispatch_once(&onceToken, ^{
        
        previousVersion = [[NSUserDefaults standardUserDefaults] objectForKey:kESUserDefaultsKey_CheckFreshLaunchAppVersion];
        
        NSString *current = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        
        if (previousVersion) {
            _isFreshLaunch = NO;
        }
        else{
            _isFreshLaunch = YES;
            [[NSUserDefaults standardUserDefaults] setObject:current forKey:kESUserDefaultsKey_CheckFreshLaunchAppVersion];
        }
        
    });
    
    return _isFreshLaunch;
}

- (void)firstLaunch{
    
    if ([CreditCore isFreshLaunch:NULL]) {
        GuideViewController *splash = [[GuideViewController alloc]init];
        UINavigationController *naV = [[UINavigationController alloc]initWithRootViewController:splash];
        [[CreditCore mainWindow] setRootViewController:naV];
    }
    else{
        [self loadMainTabbarController];
    }
    
}

- (void)loadMainTabbarController{

    if (![[CurrentUser mine] hasLogged]) {
        LoginViewController *login = [[LoginViewController alloc]init];
        UINavigationController *naV = [[UINavigationController alloc]initWithRootViewController:login];
        [[CreditCore mainWindow] setRootViewController:naV];
    }
    else{
        if (!self.mainTabbarController) {
            self.mainTabbarController = [[MainTabBarController alloc]init];
            [[CreditCore mainWindow] setRootViewController:self.mainTabbarController];
        }
    }
    

}








@end
